import sys
import time
import subprocess

def dealSampleSheet(samplesheet):
    with open(samplesheet) as ssf:
        _samples = []
        flag = 0
        for i in ssf:
            if flag == 0:
                if i.startswith('Sample_ID'):
                    flag = 1
                    continue
                continue
            if flag == 1:
                _samples.append(i.split(',')[0])
        return _samples

def main(sh):
    samples = dealSampleSheet(sh)
    ss = len(samples)
    n = 0
    while 1:
        for i in samples[:]:
            a = subprocess.run(f'ls {sys.argv[2]}/{i}/*.nt.ra.xls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if a.returncode != 0:
                time.sleep(10)
                continue
            samples.remove(i)
            n += 1
            time.sleep(10)
        if n == ss:
            break
    time.sleep(30)
    subprocess.run(f'/home/yong_sun/bin/workflow/venv/bin/python /home/yong_sun/bin/workflow/mergeNT.py {sys.argv[2]} {sys.argv[3]} {sys.argv[4]}', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    name = sys.argv[2].rstrip('/').split('/')[-1]
    subprocess.run(f'''\
cd {sys.argv[2]} && cp */*.nt.ra.xls /data/pub/today/guangzhou/{name}/ra/ && cp */*.parse.xls /data/pub/today/guangzhou/{name}/nt/
cp *.mergeNT.xlsx *.merge.NT.xls /data/pub/today/guangzhou/{name}/ 
/data/mngsSYS/b/venv/bin/python /data/softwares/mngs_scripts/auto/0727/autoGZ.py /data/pub/today/guangzhou/{name} NT && cd /data/pub/today/guangzhou/ && tar zcvf {name}.tar.gz {name}''', shell=True)

if __name__ == "__main__":
    main(sys.argv[1])
